from flask import Blueprint, render_template, request, jsonify
from app.utils.data_processor import DataProcessor
import os
from app.config import Config
import pandas as pd
from datetime import datetime

data_bp = Blueprint('data', __name__, url_prefix='/data')
data_processor = DataProcessor()


@data_bp.route('/', methods=['GET'])
def index():
    """数据管理页面"""
    datasets = []
    if os.path.exists(Config.DATA_FOLDER):
        for file in os.listdir(Config.DATA_FOLDER):
            if file.endswith(('.csv', '.xlsx', '.xls')):
                file_path = os.path.join(Config.DATA_FOLDER, file)
                file_size = os.path.getsize(file_path) / 1024  # KB
                modified_time = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S')
                datasets.append({
                    'name': file,
                    'size': f"{file_size:.1f} KB",
                    'modified': modified_time
                })

    return render_template('data.html', datasets=datasets)


@data_bp.route('/preview/<filename>')
def preview_data(filename):
    """预览数据集"""
    try:
        file_path = os.path.join(Config.DATA_FOLDER, filename)
        df = data_processor.load_data(file_path)

        return jsonify({
            'status': 'success',
            'columns': df.columns.tolist(),
            'data': df.head(10).to_dict('records'),
            'shape': df.shape
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 400


@data_bp.route('/delete/<filename>', methods=['POST'])
def delete_data(filename):
    """删除数据集"""
    try:
        file_path = os.path.join(Config.DATA_FOLDER, filename)
        if os.path.exists(file_path):
            os.remove(file_path)
            return jsonify({
                'status': 'success',
                'message': '文件删除成功'
            })
        else:
            return jsonify({
                'status': 'error',
                'message': '文件不存在'
            }), 404
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 400
